﻿using Nancy;
using Nancy.Hosting.Aspnet;
using Newtonsoft.Json;
using System;
using System.IO;

namespace TaskManagementSystem
{
    public class ErrorResponse
    {
        private readonly Error error;

        private ErrorResponse(Error error)
        {
            this.error = error;
        }

        public string ErrorMessage { get { return error.ErrorMessage; } }
        public string FullException { get { return error.FullException; } }
        public string[] Errors { get { return error.Errors; } }
        public HttpStatusCode StatusCode { get; set; }

        public static ErrorResponse FromException(Stream stream, Exception ex, HttpStatusCode StatusCode)
        {
            var statusCode = HttpStatusCode.InternalServerError;
            var error = new Error { ErrorMessage = ex.Message, FullException = ex.ToString() };

            if (StatusCode == HttpStatusCode.NotFound)
            {
                statusCode = HttpStatusCode.NotFound;
                error.FullException = null;
            }

            if (StatusCode == HttpStatusCode.Forbidden)
            {
                statusCode = HttpStatusCode.Forbidden;
                error.FullException = null;
            }

            var response = new ErrorResponse(error);
            response.StatusCode = statusCode;
            return response;
        }

        public static ErrorResponse FromException(Stream stream, Exception ex)
        {
            var statusCode = HttpStatusCode.InternalServerError;
            var error = new Error { ErrorMessage = ex.Message, FullException = ex.StackTrace };
            var response = new ErrorResponse(error);
            response.StatusCode = statusCode;
            return response;
        }

        public static ErrorResponse FromMessage(Stream stream, string message)
        {
            return new ErrorResponse(new Error { ErrorMessage = message });
        }

        public static void FromMessagePath(Stream stream, string path)
        {
            var filename = Path.Combine(new AspNetRootPathProvider().GetRootPath(), path);
            using (var file = File.OpenRead(filename))
            {
                file.CopyTo(stream);
            }
        }

        public override string ToString()
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(this.error);
        }

        private class Error
        {
            public string ErrorMessage { get; set; }

            [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
            public string FullException { get; set; }

            [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
            public string[] Errors { get; set; }
        }
    }
}